<?php
namespace jy_mlianfee;
defined('BY_JYA') or exit('error');
/*
	股东分红计算
	
*/
class commission extends \plugin{
	/*
		商户带货分润。生态抽成
	*/
	function create($order){
		if(!$this->setting['isopen']){
			return false;
		}
		$this->order=$order;
		$this->model('member')->update_agent_level($order['mid']);
		if(!$this->setting['lianrate_type'] && !$this->order['merchid']){
			return false;
		}
		if($this->setting['lianrate_type']==1 && $this->order['merchid']){
			return false;
		}
		$member=pdo_get('jy_merch_member',array('merchid'=>$this->order['merchid'],'mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']),array('fmerchid','id','mid'));
		$merchset=pdo_get('jy_mlianfee_merch',array('merchid'=>$this->order['merchid'],'uniacid'=>$_SESSION['uniacid']));
		if(!$merchset['id']){
			$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'merchid'=>$this->order['merchid'],
			);
			$this->insert('merch',$data);
		}
		//带货
		$this->create_merchfee($member,$merchset);
		//培育
		$this->create_zsfee($member,$merchset);
		//生态抽成
		$this->create_cifee($member,$merchset);
		return true;
	}
	/*
		带货
	*/
	public function create_merchfee($member=array(),$merchset=array(),$level=array()){
		if(!$member['fmerchid']){
			return false;
		}
		$agent=pdo_get('jy_merch_user',array('id'=>$this->order['merchid'],'uniacid'=>$_SESSION['uniacid']),'mid');
		$newmember=pdo_get('jy_mlianfee_member',array('mid'=>$agent['mid'],'uniacid'=>$_SESSION['uniacid']));
		if($newmember['level_id']){
			$level=pdo_get('jy_mlianfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$newmember['level_id']));
		}else{
			$level=$this->plugin_setting('default_level');
		}
		$memberrate=$merchset['memberrate'] && $merchset['memberrate']!=0.00?$merchset['memberrate']:$level['memberrate'];
		if(!$memberrate){
			return false;
		}
		$order_price=$this->order['price'];
		if($order_price>0){
			if(substr($memberrate,-1)=='%'){
				$moneyfee =($order_price*substr($memberrate,0,-1))/100;
			}else{
				$moneyfee =$memberrate;
			}
		}
		if($moneyfee >0){
			$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'merchid'=>$this->order['merchid'],
						'mid'=>$agent['mid'],
						'ordersn'=>$this->order['ordersn'],
						'orderprice'=>$this->order['price'],
						'money'=>$moneyfee,
						'remark'=>'商户带货分润',
						'createtime'=>TIMESTAMP,
						'status'=>$this->setting['is_jiesuan']?:0,
						'type'=>0,
			);
			$this->insert('commission',$new_commission);
		}
		return true;
	}
	/*
		培育员
	*/
	public function create_zsfee($member=array(),$merchset=array(),$level=array()){
		if(!$merchset['zhaoshangmid']){
			return false;
		}
		$newmember=pdo_get('jy_mlianfee_member',array('mid'=>$merchset['zhaoshangmid'],'uniacid'=>$_SESSION['uniacid']));
		if($newmember['level_id']){
			$level=pdo_get('jy_mlianfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$newmember['level_id']));
		}else{
			$level=$this->plugin_setting('default_level');
		}
		$zsrate=$merchset['zsrate'] && $merchset['zsrate']!=0.00?$merchset['zsrate']:$level['zsrate'];
		if(!$zsrate){
			return false;
		}
		$order_price=$this->order['price'];
		if($order_price>0){
			if(substr($zsrate,-1)=='%'){
				$moneyfee =($order_price*substr($zsrate,0,-1))/100;
			}else{
				$moneyfee =$zsrate;
			}
		}
		if($moneyfee >0){
			$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'merchid'=>$this->order['merchid'],
						'mid'=>$merchset['zhaoshangmid'],
						'ordersn'=>$this->order['ordersn'],
						'orderprice'=>$this->order['price'],
						'money'=>$moneyfee,
						'remark'=>'培育员分润',
						'createtime'=>TIMESTAMP,
						'status'=>$this->setting['is_jiesuan']?:0,
						'type'=>2,
			);
			$this->insert('commission',$new_commission);
		}
		return true;
	}
	/*
		会员池
	*/
	public function create_cifee($member=array(),$merchset=array(),$level=array()){
		$newmember=pdo_get('jy_mlianfee_member',array('mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if($newmember['level_id']){
			$level=pdo_get('jy_mlianfee_level',array('uniacid'=>$_SESSION['uniacid'],'id'=>$newmember['level_id']));
		}else{
			$level=$this->plugin_setting('default_level');
		}
		$cirate=$merchset['cirate'] && $merchset['cirate']!=0.00?$merchset['cirate']:$level['cirate'];
		if(!$cirate){
			return false;
		}
		$order_price=$this->order['price'];
		if($order_price>0){
			if(substr($cirate,-1)=='%'){
				$moneyfee =($order_price*substr($cirate,0,-1))/100;
			}else{
				$moneyfee =$cirate;
			}
		}
		if($moneyfee >0){
			$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'merchid'=>$this->order['merchid'],
						'mid'=>$this->order['mid'],
						'ordersn'=>$this->order['ordersn'],
						'orderprice'=>$this->order['price'],
						'fee'=>$moneyfee,
						'createtime'=>TIMESTAMP,
						'type'=>0,
			);
			$this->insert('cifeelog',$new_commission);
			pdo_update('jy_mlianfee_merch',array('cifee +='=>$moneyfee),array('merchid'=>$this->order['merchid'],'uniacid'=>$_SESSION['uniacid']));
		}
		return true;
	}
	/*
		订单完成时，把分红状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn'],'status'=>0));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		$type=intval($post['type']);
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='downline'){
			if(!$post['wechat']){
				exi('请先填写微信号！','error');
			}
			if(!$post['mobile']){
				exi('请先填写联系电话！','error');
			}
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
			$typetitle='支付宝';
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请输入银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='银行卡';
		}
		if($post['pay_type']=='jiaoyi'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankcard']){
				exi('请输入交易所账户','error');
			}
			if(!$post['bankcard1']){
				exi('请确认交易所账户','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
			$typetitle='交易所账户';
		}
		//获取可结算分红
		$params=array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		if($type){
			$params['type']=$type;
			$isgetfee=$this->model('member')->check_isgetfee($mid,$type);
			if($isgetfee){
				exi('您已结算过了该奖金！不能再结算！','error');
			}
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的分红！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		$jifen=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
			$jifen+=$commission['jifen'];
		}
		//结算最低分红检测
		if($money<$this->setting['balance_fee']){
			exi('满￥'.$this->setting['balance_fee'].'才可结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'merchid'=>$_SESSION['onemerchid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'jifen'=>$jifen,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'createtime'=>TIMESTAMP,
			'fee_type'=>$type,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid=0,$pay_trade_no=''){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$balance['merchid']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no?:$pay_trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		if($balance['jifen']>0){
			if($balance['merchid']){
				model('jy_merch/member')->member_credit($balance['merchid'],$balance['mid'],'credit1',$balance['jifen'],true,'jy_mjifee','佣金转积分');
			}else{
				cfc('core')->member_credit($balance['mid'],'credit1',$balance['jifen'],true,'jy_mjifee',$remark='佣金转积分');
			}
		}
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn,$merchid=0){
		if($merchid){
			model('jy_merch/member')->member_credit($merchid,$mid,'credit2',$money,true,'jy_mjifee','分销分红打款');
		}else{
			cfc('core')->member_credit($mid,'credit2',$money,true,'jy_mjifee',$remark='分销分红打款');
		}
		return true;
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$merchid=0){
		if($merchid){
			exi('商户不支持打款微信零钱！','error');
		}
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'员工商分红发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn,$merchid=0){
		return '';
		//exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn,$merchid=0){
		return '';
		//exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，分红规则【{$goods['commission_per']}】，分销分红【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_mjifee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
股东等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，分红等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立分红：
{$goods_str}
订单分红：
除去设置独立分红的商品外订单金额【{$remark['order_commission']['order_price']}】，分红规则【{$remark['order_commission']['commission_per']}%】，分销分红【{$remark['order_commission']['commission_money']}】
分红总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}